<?php

namespace App\Http\Controllers;

use App\UserAddress;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserAddressController extends BaseController
{
    /**
     * 获取用户地址列表
     */
    public function getList(){
        $this->uid = \session('uid');
        $list = DB::table('users_address')->where('uid', '=', $this->uid)->get();
        return returnJson(0, '', $list);
    }

    /**
     * 获取单个地址信息
     * @param $id
     */
    public function getOne($id){
        $address = DB::table('users_address')->where('id', '=', $id)->first();
        return returnJson(0, '', $address);
    }

    /**
     * 删除单个地址信息
     * @param $id
     */
    public function delOne($id){
        DB::table('users_address')->where('id', '=', $id)->delete();
        return returnJson();
    }

    /**
     * 修改或删除该条数据
     * @param \Request $request
     */
    public function save(Request  $request){
        $uid = \session('uid');
        $id = intval($request->id);
        $title = $request->title;
        $address = $request->address;
        $lat = $request->lat;
        $lnt = $request->lnt;
        if( !$uid || !$title || !$address || !$lat || !$lnt ){
            return returnJson(1, "参数缺失");
        }

        $data = [
            'uid'   => $uid,
            'title'   => $title,
            'address'   => $address,
            'lat'   => $lat,
            'lnt'   => $lnt,
        ];
        if( $id ){
//            查询该数据
            $count = DB::table('users_address')->where([['id', $id], ['uid', $uid]])->count();
            if( $count ){
//                修改数据
                UserAddress::where('id', $id)->update($data);
                return returnJson();
            }else{
                return returnJson(1, '修改的该数据不存在');
            }
        }

//        添加新数据
        $data['created_at'] = date('Y-m-d H:i:s');
        DB::table('users_address')->insert($data);
        return returnJson();
    }
}
